<!--
 * @Author: zhang ke
 * @Date: 2025-06-24 16:01:25
 * @LastEditors: your name
 * @LastEditTime: 2025-06-27 11:09:17
 * @Description: 
 * @FilePath: \vue3-admin\src\views\product\trademark\index.vue
-->
<!--  -->
<template>
  <div>
    <el-card>
      <!-- 添加按钮 -->
      <template #header>
        <div class="card-header">
          <el-button v-has="`btn.Trademark.add`" type="primary" @click="changeDialog('add',{})">
            <el-icon>
              <Plus />
            </el-icon>
            添加品牌
          </el-button>
        </div>
      </template>
      <!-- table表格 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="序号" width="90" align="center" />
        <el-table-column prop="taName" label="品牌名称" max-width="200" />
        <el-table-column prop="logo" label="品牌LOGO" max-width="200">
          <template #="{ row }">
            <img :src="row.logoUrl" alt="图片丢失了~" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #default="scope">
            <el-button size="small" type="warning" icon="Edit" @click="changeDialog('edit',scope.row)">
            </el-button>
            <el-popconfirm :title="`确定删除${scope.row.taName}品牌吗？`" width="220px" @confirm="changeDeleteTradeMark(scope.row.id)">
              <template #reference>
                <el-button size="small" type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>


      <template #footer>
        <!-- 分页器 -->
        <el-pagination @current-change="getTradeMark" @size-change="sizeChange" v-model:current-page="currentPage"
          v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]" background
          layout="prev,pager,next,jumper,-> ,sizes,total" :total="total" />
      </template>

      <!-- 新增和编辑的弹框 -->
      <el-dialog v-model="outerVisible" :title="dialogTitle" width="600">
        <el-form style="width: 70%" :model="trademarkParams" :rules="rules" ref="formRef">
          <el-form-item label="品牌名称" prop="taName" lable-width="80px">
            <el-input v-model="trademarkParams.taName" placeholder="请输入品牌名称" />
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl" lable-width="80px">
            <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button plain @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>


        </template>
      </el-dialog>

    </el-card>
  </div>
</template>

<script setup lang="ts">
import {ref,onMounted, reactive,nextTick} from 'vue'
import {reqHasTradeMark,AddTradeMark,UpdateTradeMark,deleteTradeMark} from '@/api/product/trademark/index'
import type {TradeMarkResponseData,Records,TradeMark} from '@/api/product/trademark/type'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
//列表逻辑
const currentPage = ref<number>(1)
const pageSize = ref<number>(3)
const total = ref<number>(10)
let tableData = ref<Records>([])
const getTradeMark = async ()=>{
  const res:TradeMarkResponseData = await reqHasTradeMark(currentPage.value,pageSize.value)
  if(res.code == 200){
    tableData.value = res.data.records
    total.value = res.data.total
  }
}
onMounted(()=>{
  getTradeMark()
})
const sizeChange = ()=>{
  currentPage.value = 1
  getTradeMark()

}

//新增和编辑
const outerVisible = ref<boolean>(false)
const dialogTitle = ref<string>('添加品牌')
const trademarkParams = reactive<TradeMark>({
  taName:'',
  logoUrl:'',
})
const formRef = ref()
//图片上传前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4){
      return true
    }else{
      ElMessage({
        message: '上传文件大小应小于4M',
        type: 'error',
      })
    }
    
  } else  {
    ElMessage({
      message: '上传图片类型必须是PNG|JPG|GIF',
      type: 'error',
    })
    return false
  }
  return true
}
//图片上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  trademarkParams.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}
const changeDialog = (type:string,row:object)=>{
  nextTick(()=>{
    if(formRef.value){
      formRef.value.clearValidate('taName')
      formRef.value.clearValidate('logoUrl')
    }
  })
  if(trademarkParams.id){
    delete trademarkParams.id
  }
  trademarkParams.taName = ''
  trademarkParams.logoUrl = ''
  if(type == 'add'){
    dialogTitle.value = '添加品牌'
  }else{
    Object.assign(trademarkParams,row)
    dialogTitle.value = '编辑品牌'
  }
  outerVisible.value = true
}
// 取消
const cancel = ()=>{
  outerVisible.value = false
}
// 确定
const confirm = async()=>{
  await formRef.value.validate()
  //新增
  if(dialogTitle.value == '添加品牌'){
    let res =   await AddTradeMark(trademarkParams)
    if(res.code == 200){
       currentPage.value = 1
        outerVisible.value = false
      getTradeMark()
      ElMessage({
        message: '新增成功',
        type: 'success',
      })
    }else{
         outerVisible.value = false
      ElMessage({
        message: res.message,
        type: 'error',
      })
    }
  }else{
    let res =   await UpdateTradeMark({...trademarkParams})
    if(res.code == 200){
      outerVisible.value = false
      getTradeMark()
      ElMessage({
        message: '编辑成功',
        type: 'success',
      })
    }else{
      outerVisible.value = false
      ElMessage({
        message: res.message,
        type: 'error',
      })
    }
  }
}

//名称校验
const validatorTaName = (value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
///图片校验
const validatorLogoUrl = (value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('Logo的图片务必上传'))
  }
}
//表单校验
/**
 * required 是否必须校验
 * trigger 触发事件
 * validator 校验函数
 */
const rules = {
  taName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorTaName,
    },
  ],
  logoUrl: [
    {
      required: true,
      trigger: 'change',
      validator: validatorLogoUrl,
    },
  ],
}

//删除品牌
const changeDeleteTradeMark = async(id:number)=>{
  let res = await deleteTradeMark(id)
  if(res.code == 200){
      ElMessage({
        message: res.message,
        type: 'success',
      })
      //判断是不是最后一页的最后一条数据
      currentPage.value = tableData.value.length > 1 ? currentPage.value : currentPage.value - 1
       getTradeMark()
  }else{
     ElMessage({
        message: res.message,
        type: 'error',
      })
  }
  console.log('222')
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>